package com.example.joke.iv;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

public class SkewedImageView extends AppCompatImageView {

    private Matrix skewMatrix = new Matrix();

    public SkewedImageView(Context context) {
        super(context);
    }

    public SkewedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SkewedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            // 设置倾斜的角度，这里以45度为例
            float skewX = 0.5f; // 横向倾斜量，0.0表示无倾斜
            skewMatrix.reset();
            skewMatrix.setSkew(skewX, 0.0f);
            // 将Matrix应用到ImageView上
            canvas.drawBitmap(getBitmapFromDrawable(drawable), skewMatrix, null);
        } else {
            super.onDraw(canvas);
        }
    }

    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}
